import React, { useRef } from 'react';
import { Button, Form, Radio, Space, Table, Tag, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DeleteOutlined, PlusOutlined,ReloadOutlined } from '@ant-design/icons';
import { ModalForm, ProForm, ProFormText, ProFormDateRangePicker, ProFormSelect, ProFormRadio, ProFormInstance } from '@ant-design/pro-components';
import form from 'antd/es/form';
import { useModel } from 'umi';
import { Requirement } from '@/models/interfaces'



const columns: ColumnsType<Requirement> = [
  {
    title: 'Name',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'Description',
    dataIndex: 'description',
    key: 'description',
  },
  {
    title: 'Source',
    dataIndex: 'source',
    key: 'source',
  },
  {
    title: 'Header',
    dataIndex: 'header',
    key: 'header',
    render: v => <>dip={v}</>
  },
  // {
  //   title: 'Trigger Mode',
  //   dataIndex: 'mode',
  //   key: 'mode',
  // },
  // {
  //   title: 'Updated at',
  //   dataIndex: 'updatedAt',
  //   key: 'updatedAt',
  // },
  {
    title: 'Created At',
    dataIndex: 'createdAt',
    key: 'createdAt',
    render: (v:Date) => v.toLocaleString()
  },
  {
    title: 'Status',
    key: 'status',
    dataIndex: 'status',
    render: (_, { status }) => (
      <Tag color={status == 'pass' ? 'green' : 'red'}>
        {status.toUpperCase()}
      </Tag>
    ),
  },
  {
    title: 'Action',
    // key: 'action',
    render: (_, record) => (
      <Space size="middle">
        <a><DeleteOutlined/></a>
      </Space>
    ),
  },
];

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default () => {
  const [form] = Form.useForm<Requirement>();
  const { hosts, routers, requirements, addRequirement,setRequirements } = useModel('networkModel')
  const sourceOptions = Object.values(hosts).map(host => ({
    label: host.id,
    value: host.id,
  }))

  const trigger = () => {
    let reqs = []
    requirements.forEach(req => {
      req.status = 'fail';
      reqs.push(req);
    });
    setRequirements(reqs);
    fetch('http://localhost:3000/notify')
  }

  return (
    <Space direction='vertical' style={{ width: '100%' }}>
      <ModalForm<Requirement>
        title="Add Requirement"
        trigger={
          <Button type="primary">
            <PlusOutlined />
            Add Requirement
          </Button>
        }
        form={form}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => console.log('run'),
        }}
        submitTimeout={2000}
        onFinish={async (values) => {
          // await waitTime(2000);
          // const values = await formRef.current?.validateFieldsReturnFormatValue?.();
          const req: Requirement = {
            ...values,
            createdAt: new Date(),
            status: 'pass'
          }
          console.log(req);
          addRequirement(req);
          message.success('Success');
          return true;
        }}
      >
        <ProForm.Group>
          <ProFormText
            width="md"
            name="name"
            label="Name"
            tooltip="The requirement name"
            rules={[
              { required: true },
            ]}
          />

          <ProFormText
            width="md"
            name="description"
            label="Description"
          />

          <ProFormSelect
            options={sourceOptions}
            width="md"
            name="source"
            label="Source device"
            rules={[
              { required: true }
            ]}
          />

          <ProFormText
            addonBefore="dip="
            width="md"
            name="header"
            label="Header"
            rules={[
              { required: true },
              {pattern: /(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/, message: 'Invalid IP address'}
            ]}
          />
        </ProForm.Group>
        <ProFormText
          name="content"
          label="Path regex"
          initialValue=""
          rules={[
            { required: true }
          ]}
          tooltip='Enter a regular expression, e.g., Host1.*Host2'
        />
        <ProFormText
          label="Notify email"
          initialValue=""
          rules={[
            { required: true }
          ]}
          tooltip='Enter an email address'
        />
        <ProFormRadio.Group
          name="mode"
          label="Trigger mode"
          fieldProps={{
            defaultValue: 'auto',
            name: 'mode'
          }}
          options={[{
            label: 'Auto',
            value: 'auto',
          }, {
            label: 'Manual',
            value: 'manual'
          }]}
          tooltip='Auto: Automatically trigger verification when data plane changes; Manual: Trigger verification manually.'
        />

      </ModalForm>
      <Button onClick={trigger} style={{float: 'right'}} icon={<ReloadOutlined />}></Button>
      <Table rowKey='id' columns={columns} dataSource={requirements} />
    </Space>
  )
}
